# -*- coding: UTF-8 -*-
from pyLib.databaseManage import SYS_DATABASE


class EDITION(object):
    @staticmethod
    def get_edition(module_type: str, version=None):
        """
        @param: module_type - 组件类型
        @param: version - 服务版本取值字段 version = "1.0" or version = None
        version=”1.0“ 返回服务名+指定版本;
        version=None 返回服务名+最高版本;
        """
        version = version.replace("-",".")
        sql = f"""
                SELECT
                    a.server_name
                FROM
                    sys_module_server_info a
                LEFT JOIN sys_module_info b ON b.id = a.module_id
                WHERE
                    b.module_type = '{module_type}' """
        if version:
            sql += f"AND b.module_version = '{version}' LIMIT 1"
        else:
            sql += f"ORDER BY b.module_version DESC LIMIT 1"
        try:
            result = SYS_DATABASE.execute_sql(sql)
            return result[0][0]
        except IndexError:
            return "null"

    @staticmethod
    def get_module_ver(module_name: str, module_version=None):
        """
        @param: module_name - 组件名称 返回当前组件以及版本
        """
        new_version = ""
        if module_version:
            new_version = str(module_version).replace(".", "_")
        result_ser = SYS_DATABASE.get_db_data(table="sys_module_info", show_list=["id"],
                                           condition="module_type like '{}%' and id like '%{}' order by module_version DESC".format(
                                               module_name, new_version))
        if result_ser:
            return result_ser[0][0]

    @staticmethod
    def get_server_name(module_id: str):
        """
        根据组件id查询服务名
        :param module_id: 组件id
        :return: 服务名
        """
        server_name = SYS_DATABASE.execute_sql(
            f"select server_name from sys_module_server_info where module_id like '%{module_id}%'"
        )[0][0]
        return server_name


if __name__ == '__main__':
    print(EDITION.get_edition("DIM","1.1"))
